<?php
declare(strict_types=1);
namespace Service\GoodsService;
use Service\BaseService;
use App\Model\BbcModel\Goods;
use Hyperf\DbConnection\Db;
use App\Model\BbcModel\MnStoreGoods;
use Service\Code\Normal;

/**
 * 渠道商品服务中心
 * @author chenshubo
 */
class ChannelGoodsService extends BaseService
{
    /**
     * 批量获取渠道商品清单
     * @param array $goodsIds
     */
    public function queryGoodsList(array $goodsIds)
    {
        return Goods::instance()
        ->select(self::getColumn())
        ->whereIn('id',$goodsIds)
        ->get()
        ->toArray();
    }
    
    /**
     * 批量获取渠道商品清单
     * @param int $brand_id
     */
    public function queryGoodsListByBrandID(int $brand_id)
    {
        return Goods::instance()
        ->select([
            'id',
            'name',
            'class_id',
            'brand_id',
            'is_trade',
            'cid'
        ])
        ->where('status',1)
        ->where('df',0)
        ->whereIn('brand_id',$brand_id)
        ->get()
        ->toArray();
    }
    
    /**
     * 获取商品数据IDs
     * @param int $cid
     * @param array $skuCodes
     */
    public function queryGoodsListBySkuCodeAndCid(int $cid,array $skuCodes)
    {
        return Goods::instance()
        ->select([
            'id',
        ])
        ->where('cid',$cid)
        ->whereIn('skucode',$skuCodes)
        ->get()
        ->toArray();
    }
    
    /**
     * 批量获取渠道商品清单数据
     * @param array $goodsIds
     */
    public function queryGoodsPageList(int $cid)
    {
        return Goods::instance()
        ->from('ly_goods as lg')
        ->select([
            'lly_goods.id as GoodsID',
            'lly_goods.name as GoodsName',
            'lly_goods.class_id as ClassID',
            'ly_goods_batch.name as BrandName'
        ])
        ->join('ly_goods_brand as lgb','ly_goods_batch.id','=','lly_goods.brand_id')
        ->where('lly_goods.cid',$cid)
        ->where('lly_goods.status',1)
        ->where('lly_goods.df',0)
        ->get()
        ->toArray();
    }
    
    /**
     * 获取字段
     * @return string[]
     */
    private static function getColumn()
    {
        return [
            'id',
            'price_recommend',
            'price_recommend_vip',
            'price_store',
            'tax_rate',
            'tax_free',
            'price_market',
            'price_cost',
            'is_trade',
            'skucode',
            'barcode',
            'name',
            'is_bonded',
            'img',
            'num_storage',
            'supplier_name',
            'base_spec',
            'unit_name',
            'fictitious_sale',
            'num_sale',
            'medicinal',
            'pic_auth',
            'df',
            'status',
            'use_points',
            'return_points',
            'is_combine_goods',
            'combine_goods_json_body',
            'high_price',
            'high_tax_rate',
            'supplier_id',
            'is_trade',
        ];
    }

    /**
     * 获取商品数据列表
     * @param int $cid
     * @param int $mn_sid
     * @param int $status
     * @param array $goods_ids
     * @param array $mn_user
     */
    public function queryBaseGoodsList(int $cid,int $mn_sid,int $status,array $goods_ids,array $mn_user)
    {
        //商品信息
        $fields = [
            "ly_goods.id",
            "ly_goods.name",
            "ly_goods.img",
            "ly_goods.class_id",
            "ly_goods.brand_id",
            "ly_goods.skucode",
            "ly_goods.is_trade",
            "ly_goods.barcode",
            "ly_goods.tax_rate",
            "ly_goods.tax_free",
            "ly_goods.status",
            "ly_goods.is_bonded",
            "ly_goods.is_sync",
            "ly_goods.price_store",
            "ly_goods.cid",
            "ly_goods.price_recommend",
            "ly_goods.price_recommend_vip",
            "ly_goods.body",
            "ly_goods.price_cost",
            "ly_goods.num_storage",
            "ly_goods.price_market",
            "ly_goods.fictitious_sale",
            "ly_goods.num_sale",
            "ly_goods.df",
            "ly_goods.medicinal",
            "ly_goods.tag",
            "ly_goods.supply_tag",
            "ly_goods.pic_auth",
            "ly_goods.base_spec",
            "ly_goods.price",
            "ly_goods_batch.spec_list",
            "ly_goods_batch.batch_no",
            "ly_goods_batch.storage_id",
            "ly_goods_batch.num",
            "ly_mn_store_goods.num as mn_num",
            "ly_mn_store_goods.pre_sell as mn_pre_sell",
            "ly_mn_store_goods.up as mn_up",
            "ly_mn_store_goods.up as mn_pre_storage",
            "ly_mn_store_goods.status as mn_status",
            "ly_mn_store_goods.profit",
            "ly_mn_store_goods.profit_vip",
            "ly_mn_store_goods.type",
            "ly_mn_store_goods.price_vip",
        ];

        $goodsList = Goods::instance()
            ->leftJoin('ly_mn_store_goods',"ly_mn_store_goods.goods_id","=","ly_goods.id")
            ->leftJoin('ly_goods_batch',"ly_goods_batch.goods_id", "=", "ly_goods.id")
            ->select($fields)
            ->selectRaw("IF(ly_goods.is_trade = 1,ly_goods_batch.mn_sid = {$mn_sid} AND ly_goods_batch.type = 1,ly_goods_batch.type = 0)")
            ->whereIn('ly_goods.id',$goods_ids)
            ->where('ly_goods.status',$status)
            ->where('ly_goods.df',0)
            ->where('ly_mn_store_goods.mn_sid',$mn_sid)
            ->where('ly_mn_store_goods.status',1)
            ->where(function ($query) use ($mn_user){
                if($mn_user['type'] == 2){
                    $query->selectRaw(Db::raw("((ly_goods.status=1 and ly_goods.df=0 and ly_goods.is_trade=0) or (ly_goods.is_trade=1 and (ly_mn_store_goods.df=0 or (ly_mn_store_goods.df=1 and ly_mn_store_goods.num>0) or (ly_mn_store_goods.pre_sell=1 and ly_mn_store_goods.pre_storage>0))))"));
                }else{
                    $query->selectRaw(Db::raw("ly_goods.is_trade=0"));
                }
            })
            ->where(function ($query) use ($mn_user){
                if($mn_user['type']==3){
                    switch ($mn_user['goods_source']){
                        case 1://只卖普通仓
                            $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery=0)"));
                            break;
                        case 2://只卖前置仓
                            $query->selectRaw(Db::raw("(ly_goods.supplier_id=$mn_user[supplier_id])"));
                            break;
                        case 3://前置仓+普通仓
                            $query->selectRaw(Db::raw("((ly_goods.supplier_id=$mn_user[supplier_id]) or (ly_goods.is_fast_delivery=0))"));
                            break;
                        case 4://只卖中心仓
                            $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery=2)"));
                            break;
                        case 5://中心仓+普通仓
                            $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery<>1)"));
                            break;
                        case 6://中心仓+前置仓
                            $query->selectRaw(Db::raw("((ly_goods.supplier_id=$mn_user[supplier_id]) or (ly_goods.is_fast_delivery=2))"));
                            break;
                        case 7://所有仓
                            $query->selectRaw(Db::raw("((ly_goods.supplier_id=$mn_user[supplier_id]) or (ly_goods.is_fast_delivery in (0,2)))"));
                            break;
                    }
                }else{
                    $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery <> 1)"));
                }
            })
            ->get()->toArray();
        /*        $goodsBatch = Goodsbatch::instance()
                    ->where('goods_id','in',$goods_ids)
                    ->where(['type'=>1, 'df' => 0,'mn_sid'=>$mn_sid])
                    ->field('spec_list,batch_no')
                    ->select()
                    ->toArray();*/
        $goodsListGroup = [];
        foreach ($goodsList as $goods)
        {
            $goods_id = $goods['id'];
            /*$batchList[$goods_id][$goods['batch_no']] = [
                'spec_list'  => $goods['spec_list'],
                'batch_no'   => $goods['batch_no'],
            ];
            unset($goods['spec_list'],$goods['batch_no']);
            $goods['batchList'] = $batchList;*/
            $goodsListGroup[$goods_id] = $goods;
        };
        //计算商品收益率
        //店铺等级
        $mn_user_level = $mn_user['level'];
        $profitGoodsPriceLists = MnGoodsService::instance()->getGoodsAllProfit($mn_sid,$goods_ids,1,$mn_user_level);
        $profitGoodsPriceListMap = array_column($profitGoodsPriceLists,null,'goods_id');

        //批量获取品牌数据
        $brand_ids = array_column($goodsListGroup,'brand_id');
        $goodsBrandList = GoodsBrandService::instance()->getBrandList($brand_ids);
        $goodsBrandListMap = array_column($goodsBrandList,null,'id');

        //分类查询
        $class_ids = array_column($goodsListGroup,'class_id');
        $classList = GoodsClassService::instance()->getClassList($class_ids);
        $classListMap = array_column($classList,null,'id');

        //商品标签
        $goodsTagList = GoodsTagsService::instance()->getGoodsTagsList($cid);

        //处理商品列表
        $newGoodsList = [];
        $mnGoodsList = MnStoreGoods::instance()
            ->where(['mn_sid'=>$mn_sid])
            ->where('goods_id','in',$goods_ids)
            ->select(explode(',','goods_id,num,pre_storage'))
            ->get()->toArray();
        $mnGoods = array_column($mnGoodsList,null,'goods_id');
        foreach ($goodsListGroup as & $goods)
        {


            $goods['status']    = $goods['mn_status']??0;
            $goods['up']        = $goods['mn_up']??0;
            $goods['pre_sell']  = $goods['mn_pre_sell']??0;

            $spec_list = (isset($goods['spec_list']) && $goods['spec_list']) ? json_decode($goods['spec_list'], true) : '1';
            $baseSpec = 1;
            if(!empty($spec_list)){
                $baseSpec = $spec_list[0]['spec_num'] ?? 1;
            }
            /*$currentBatch   = current($goods['batchList']);
            $has_batch      = current($currentBatch);
            $spec_list      = isset($has_batch['spec_list']) && !empty($has_batch['spec_list']) ? json_decode($has_batch['spec_list'], 1) : '';
            $baseSpec       = 1;
            if(!empty($spec_list)){
                $baseSpec = $spec_list[0]['spec_num']??1;
            }*/
            $has_batch['num']        = $goods['num'];
            $has_batch['storage_id'] = $goods['storage_id'];
            $has_batch['spec_list']  = $goods['spec_list'];
            $has_batch['batch_no']   = $goods['batch_no'];
            $goods['num_storage']    = $goods['num'] ?? 0;
            $goods['stoid']          = $goods['storage_id'] ?? 0;
            if( $goods['is_trade'] == 1 ) {
                $goods['num_storage'] = $mnGoods[$goods['id']]['num']??0;
            }

            //预售库存
            if( $goods['pre_sell'] == 1 ) {
                $goods['num_storage'] = $mnGoods[$goods['id']]['pre_storage'];
            }

            //C端价格
            if(!isset($profitGoodsPriceListMap[$goods['id']])){ //商品在店铺商品表不存在
                continue;
            }
            $profit                         = $profitGoodsPriceListMap[$goods['id']] ?? [];
            $goods['price_market']          = $profit['price_market'] ?? $goods['price_market'];
            $goods['price_store']           = $profit['price_store'] ?? $goods['price_store'];
            $goods['price_cost']            = sprintf("%.2f", round($goods['price_store'], 2));
            $goods['price_recommend']       = sprintf("%.2f", round($goods['price_recommend'], 2));
            $goods['price_recommend_vip']   = sprintf("%.2f", round($goods['price_recommend_vip'], 2));
            $goods['price']                 = sprintf("%.2f", round($profit['profit']  + $goods['price_store'], 2));
            $goods['profit']                = sprintf("%.2f", round($profit['profit'], 2));
            $goods['price_vip']             = sprintf("%.2f", round($profit['profit_vip']  + $goods['price_store'], 2));
            $goods['profit_vip']            = sprintf("%.2f", round($profit['profit_vip'], 2));

            //品牌
            $brand = $goodsBrandListMap[$goods['brand_id']] ?? [];

            //分类
            $class = $classListMap[$goods['class_id']] ?? [];
            //处理商品图片
            if (!empty($goods['img']) && strpos($goods['img'],'http')===false) {
                $goods['img'] = pre_image_url(). $goods['img'] . pic_level()['small_resize'];
            }

            //标签问题
            $label = GoodsTagsService::instance()->getGoodsTags($goodsTagList, $goods);

            $data  = [
                'id'                => $goods['id'],
                'name'              => $goods['name'],
                'img'               => $goods['img'],
                'body'              => $goods['body'],
                'barcode'           => $goods['barcode'],
                'skucode'           => $goods['skucode'],
                'is_trade'          => $goods['is_trade'],
                'is_bonded'         => $goods['is_bonded'],
                'num_sale'          => $goods['fictitious_sale'],
                'num_storage'       => $goods['num_storage'],
                'class_name'        => $class['name'] ?? '',
                'class_id'          => $class['id'] ?? '',
                'brand_name'        => !empty($brand['name']) ? $brand['name'] : '',
                'brand_id'          => $brand['id'] ?? '',
                'brand_country_name'=> !empty($brand['country_name']) ? $brand['country_name'] : '',
                'brand_country_icon'=> !empty($brand['country_icon']) ? $brand['country_icon'] : '',
                'is_sync'           => $goods['is_sync'],
                'stoid'             => $goods['stoid'],
                'baseSpec'          => $baseSpec,
                'price'             => $goods['price'],
                'price_vip'         => $goods['price_vip'],
                'price_store'       => $goods['price_store'],
                'price_cost'        => $goods['price_cost'],
                'price_recommend'   => $goods['price_recommend'],
                'price_recommend_vip'   => $goods['price_recommend_vip'],
                'price_market'      => $goods['price_market'],
                'profit'            => $goods['profit'],
                'profit_vip'        => $goods['profit_vip'],
                'has_batch'         => $has_batch,
                'status'            => $goods['status'],
                'df'                => $goods['df'],
                'is_medicinal'      => $goods['pic_auth'],
                'medicinal'         => $goods['medicinal'],
                'up'                => $goods['up'],
                'pre_sell'          => $goods['pre_sell'],
                'tax_free'          => $goods['tax_free'],
                'tax_rate'          => $goods['tax_rate'],
                'type'              => $goods['type'],
                'base_spec'         => $goods['base_spec'],
                'label'             => $label,
            ];
            if (!empty($data['brand_country_icon']) && strpos($data['brand_country_icon'],'http')===false) {
                $data['brand_country_icon'] = pre_image_url(). $data['brand_country_icon'];
            }

            array_push($newGoodsList, $data);
        }
        return $newGoodsList;
    }
}
